const db = require('../config/database');
const logger = require('../config/logger');

/**
 * 获取传输任务列表
 */
exports.getTransferTasks = async (req, res) => {
  try {
    const { status, userId, page = 1, limit = 20 } = req.query;
    const userType = req.user?.type || 'admin';
    const offset = (page - 1) * limit;

    let query = `
      SELECT
        t.*,
        u.username,
        t.file_size,
        t.transferred as transferred_size,
        t.speed,
        t.progress
      FROM transfer_tasks t
      LEFT JOIN users u ON t.user_id = u.id
      WHERE 1=1
    `;

    let countQuery = 'SELECT COUNT(*) as total FROM transfer_tasks t WHERE 1=1';
    const params = [];

    // 普通用户只能看自己的任务
    if (userType === 'user') {
      query += ' AND t.user_id = ?';
      countQuery += ' AND t.user_id = ?';
      params.push(req.user.id);
    } else if (userId) {
      query += ' AND t.user_id = ?';
      countQuery += ' AND t.user_id = ?';
      params.push(userId);
    }

    // 状态筛选
    if (status) {
      query += ' AND t.status = ?';
      countQuery += ' AND t.status = ?';
      params.push(status);
    }

    // 获取总数
    const [countResult] = await db.query(countQuery, params);
    const total = countResult[0].total;

    // 分页查询
    query += ' ORDER BY t.created_at DESC LIMIT ? OFFSET ?';
    const [tasks] = await db.query(query, [...params, parseInt(limit), offset]);

    res.json({
      success: true,
      data: {
        tasks,
        total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    logger.error('获取传输任务列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取传输任务列表失败'
    });
  }
};

/**
 * 获取活动传输任务（正在传输的）
 */
exports.getActiveTransfers = async (req, res) => {
  try {
    const userType = req.user.type;

    let query = 'SELECT * FROM v_active_transfers';
    const params = [];

    // 普通用户只能看自己的任务
    if (userType === 'user') {
      query += ' WHERE user_id = ?';
      params.push(req.user.id);
    }

    query += ' ORDER BY started_at DESC';

    const [tasks] = await db.query(query, params);

    res.json({
      success: true,
      data: tasks
    });
  } catch (error) {
    logger.error('获取活动传输任务失败:', error);
    res.status(500).json({
      success: false,
      message: '获取活动传输任务失败'
    });
  }
};

/**
 * 更新任务状态
 */
exports.updateTaskStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    // 检查任务是否存在
    const [tasks] = await db.query('SELECT * FROM transfer_tasks WHERE id = ?', [id]);
    if (tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在'
      });
    }

    const task = tasks[0];

    // 普通用户只能控制自己的任务
    if (req.user.type === 'user' && task.user_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: '无权操作此任务'
      });
    }

    // 更新状态
    let updateQuery = 'UPDATE transfer_tasks SET status = ?, updated_at = NOW()';
    const params = [status];

    if (status === 'completed') {
      updateQuery += ', completed_at = NOW()';
    } else if (status === 'transferring') {
      updateQuery += ', started_at = NOW()';
    }

    updateQuery += ' WHERE id = ?';
    params.push(id);

    await db.query(updateQuery, params);

    // 通知客户端（通过WebSocket）
    const socketManager = req.app.get('socketManager');
    if (socketManager) {
      socketManager.sendTaskControl(task.user_id, {
        action: 'status_change',
        taskId: id,
        status
      });
    }

    logger.info(`任务状态更新: ${id} -> ${status}`);

    res.json({
      success: true,
      message: '状态更新成功'
    });
  } catch (error) {
    logger.error('更新任务状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新任务状态失败'
    });
  }
};

/**
 * 取消任务
 */
exports.cancelTask = async (req, res) => {
  try {
    const { id } = req.params;

    // 检查任务
    const [tasks] = await db.query('SELECT * FROM transfer_tasks WHERE id = ?', [id]);
    if (tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在'
      });
    }

    const task = tasks[0];

    // 权限检查
    if (req.user.type === 'user' && task.user_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: '无权操作此任务'
      });
    }

    // 更新状态为已取消
    await db.query(
      'UPDATE transfer_tasks SET status = "cancelled", updated_at = NOW() WHERE id = ?',
      [id]
    );

    // 删除未完成的分片
    await db.query('DELETE FROM file_chunks WHERE task_id = ?', [id]);

    // 通知客户端
    const socketManager = req.app.get('socketManager');
    if (socketManager) {
      socketManager.sendTaskControl(task.user_id, {
        action: 'cancel',
        taskId: id
      });
    }

    logger.info(`任务已取消: ${id}`);

    res.json({
      success: true,
      message: '任务已取消'
    });
  } catch (error) {
    logger.error('取消任务失败:', error);
    res.status(500).json({
      success: false,
      message: '取消任务失败'
    });
  }
};

/**
 * 暂停任务
 */
exports.pauseTask = async (req, res) => {
  try {
    const { id } = req.params;

    const [tasks] = await db.query('SELECT * FROM transfer_tasks WHERE id = ?', [id]);
    if (tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在'
      });
    }

    const task = tasks[0];

    if (req.user.type === 'user' && task.user_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: '无权操作此任务'
      });
    }

    await db.query(
      'UPDATE transfer_tasks SET status = "paused", updated_at = NOW() WHERE id = ?',
      [id]
    );

    const socketManager = req.app.get('socketManager');
    if (socketManager) {
      socketManager.sendTaskControl(task.user_id, {
        action: 'pause',
        taskId: id
      });
    }

    logger.info(`任务已暂停: ${id}`);

    res.json({
      success: true,
      message: '任务已暂停'
    });
  } catch (error) {
    logger.error('暂停任务失败:', error);
    res.status(500).json({
      success: false,
      message: '暂停任务失败'
    });
  }
};

/**
 * 恢复任务
 */
exports.resumeTask = async (req, res) => {
  try {
    const { id } = req.params;

    const [tasks] = await db.query('SELECT * FROM transfer_tasks WHERE id = ?', [id]);
    if (tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在'
      });
    }

    const task = tasks[0];

    if (req.user.type === 'user' && task.user_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: '无权操作此任务'
      });
    }

    await db.query(
      'UPDATE transfer_tasks SET status = "transferring", updated_at = NOW() WHERE id = ?',
      [id]
    );

    const socketManager = req.app.get('socketManager');
    if (socketManager) {
      socketManager.sendTaskControl(task.user_id, {
        action: 'resume',
        taskId: id
      });
    }

    logger.info(`任务已恢复: ${id}`);

    res.json({
      success: true,
      message: '任务已恢复'
    });
  } catch (error) {
    logger.error('恢复任务失败:', error);
    res.status(500).json({
      success: false,
      message: '恢复任务失败'
    });
  }
};

/**
 * 批量取消任务
 */
exports.batchCancelTasks = async (req, res) => {
  try {
    const { taskIds } = req.body;

    if (!Array.isArray(taskIds) || taskIds.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供任务ID列表'
      });
    }

    // 检查权限
    if (req.user.type === 'user') {
      const [tasks] = await db.query(
        'SELECT id FROM transfer_tasks WHERE id IN (?) AND user_id = ?',
        [taskIds, req.user.id]
      );

      if (tasks.length !== taskIds.length) {
        return res.status(403).json({
          success: false,
          message: '无权操作部分任务'
        });
      }
    }

    // 批量取消
    await db.query(
      'UPDATE transfer_tasks SET status = "cancelled", updated_at = NOW() WHERE id IN (?)',
      [taskIds]
    );

    await db.query('DELETE FROM file_chunks WHERE task_id IN (?)', [taskIds]);

    logger.info(`批量取消任务: ${taskIds.join(', ')}`);

    res.json({
      success: true,
      message: `成功取消 ${taskIds.length} 个任务`
    });
  } catch (error) {
    logger.error('批量取消任务失败:', error);
    res.status(500).json({
      success: false,
      message: '批量取消任务失败'
    });
  }
};

/**
 * 获取任务详情
 */
exports.getTaskDetail = async (req, res) => {
  try {
    const { id } = req.params;

    const [tasks] = await db.query(
      'SELECT t.*, u.username FROM transfer_tasks t LEFT JOIN users u ON t.user_id = u.id WHERE t.id = ?',
      [id]
    );

    if (tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在'
      });
    }

    const task = tasks[0];

    // 权限检查
    if (req.user.type === 'user' && task.user_id !== req.user.id) {
      return res.status(403).json({
        success: false,
        message: '无权查看此任务'
      });
    }

    // 获取分片信息
    const [chunks] = await db.query(
      'SELECT chunk_index, is_uploaded FROM file_chunks WHERE task_id = ? ORDER BY chunk_index',
      [id]
    );

    res.json({
      success: true,
      data: {
        ...task,
        chunks
      }
    });
  } catch (error) {
    logger.error('获取任务详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取任务详情失败'
    });
  }
};

/**
 * 获取传输统计
 */
exports.getTransferStats = async (req, res) => {
  try {
    const [uploading] = await db.query(
      'SELECT COUNT(*) as count FROM transfer_tasks WHERE status = "uploading"'
    );

    const [downloading] = await db.query(
      'SELECT COUNT(*) as count FROM transfer_tasks WHERE status = "downloading"'
    );

    const [waiting] = await db.query(
      'SELECT COUNT(*) as count FROM transfer_tasks WHERE status = "waiting"'
    );

    const [failed] = await db.query(
      'SELECT COUNT(*) as count FROM transfer_tasks WHERE status = "failed"'
    );

    res.json({
      success: true,
      data: {
        uploading: uploading[0].count,
        downloading: downloading[0].count,
        waiting: waiting[0].count,
        failed: failed[0].count
      }
    });
  } catch (error) {
    logger.error('获取传输统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取传输统计失败'
    });
  }
};

/**
 * 重试失败的任务
 */
exports.retryTask = async (req, res) => {
  try {
    const { id } = req.params;

    const [tasks] = await db.query('SELECT * FROM transfer_tasks WHERE id = ?', [id]);
    if (tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在'
      });
    }

    const task = tasks[0];

    await db.query(
      `UPDATE transfer_tasks
       SET status = "waiting",
           error_message = NULL,
           transferred_bytes = 0,
           updated_at = NOW()
       WHERE id = ?`,
      [id]
    );

    logger.info(`任务重试: ${id}`);

    res.json({
      success: true,
      message: '任务已重新开始'
    });
  } catch (error) {
    logger.error('重试任务失败:', error);
    res.status(500).json({
      success: false,
      message: '重试任务失败'
    });
  }
};

/**
 * 删除任务
 */
exports.deleteTask = async (req, res) => {
  try {
    const { id } = req.params;

    await db.query(
      'DELETE FROM transfer_tasks WHERE id = ?',
      [id]
    );

    logger.info(`任务已删除: ${id}`);

    res.json({
      success: true,
      message: '任务已删除'
    });
  } catch (error) {
    logger.error('删除任务失败:', error);
    res.status(500).json({
      success: false,
      message: '删除任务失败'
    });
  }
};

/**
 * 清空已完成的任务
 */
exports.clearCompletedTasks = async (req, res) => {
  try {
    await db.query(
      `DELETE FROM transfer_tasks
       WHERE status IN ("completed", "cancelled", "failed")`
    );

    logger.info('已清空已完成的任务');

    res.json({
      success: true,
      message: '已清空已完成的任务'
    });
  } catch (error) {
    logger.error('清空已完成任务失败:', error);
    res.status(500).json({
      success: false,
      message: '清空已完成任务失败'
    });
  }
};
